package org.jeecg.modules.openai.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.util.PemUtil;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import org.apache.commons.collections4.map.LinkedMap;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.Md5Util;
import org.jeecg.modules.openai.entity.AiOrder;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
import java.util.Date;
import java.util.LinkedHashMap;

public class WeChatPayment {

    /**
     * 商户号
     */
    public static String merchantId = "1639415880";
    /**
     * 商户API私钥路径
     */
    public static String privateKeyPath = "/payment/apiclient_key.pem";
    /**
     * 商户证书序列号
     */
    public static String merchantSerialNumber = "27FE0117F39E630107DBA3E025DC595244C78B49";
    /**
     * 商户APIV3密钥
     */
    public static String apiV3key = "pr808ho4honc2u7py2qktdku3rgenit2";

    public static String appId = "wx6df9c7a154d2abae";

    public static Config config;

    static {
        config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3key)
                        .build();
    }

    public static JSONObject createPayment(AiOrder order, String openId) {


        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKeyFromPath(privateKeyPath);

        JSONObject rp = new JSONObject();

        JsapiService service = new JsapiService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(1);
        request.setAmount(amount);
        request.setAppid(appId);
        request.setMchid(merchantId);
        request.setDescription("测试商品标题");
        request.setNotifyUrl("https://34535k530x.zicp.fun/jeecg-boot/view/openAi/webhook");
//        request.setNotifyUrl("https://www.origins.media/jeecg-boot/view/openAi/webhook");
        request.setOutTradeNo(order.getId());
        Payer payer = new Payer();
        payer.setOpenid(openId);
        request.setPayer(payer);
        PrepayResponse response = service.prepay(request);
        String nonceStr = RandomUtil.randomString(32).toUpperCase();
        String timeStamp = (new Date().getTime()/1000) + "";
        String strA = "appId=" + appId + "&nonceStr=" + nonceStr + "&package=prepay_id=" + response.getPrepayId() + "&signType=MD5&timeStamp=" + timeStamp;
        String signStr = Md5Util.md5Encode(strA + "&key=" + apiV3key, "utf-8").toUpperCase();
        String message = appId + "\n"
                + timeStamp + "\n"
                + nonceStr + "\n"
                + "prepay_id=" + response.getPrepayId() + "\n";
        Signature sign = null;

        try {
            sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(merchantPrivateKey);
            sign.update(message.getBytes("utf-8"));
            signStr = Base64.getEncoder().encodeToString(sign.sign());
//            rp.put("appId", appId);
            rp.put("timeStamp", timeStamp);
            rp.put("nonceStr", nonceStr);
            rp.put("package", "prepay_id=" + response.getPrepayId());
            rp.put("signType", "RSA");
            rp.put("paySign", signStr);
            rp.put("id",order.getId());
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }



        return rp;

    }


    public static JSONObject wxpayNotify(JSONObject jsonObject) {

        if(!"TRANSACTION.SUCCESS".equals(jsonObject.getStr("event_type"))){
            return null;
        }

        String key = apiV3key;
        String json = jsonObject.toString();
        String associated_data = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.associated_data");
        String ciphertext = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.ciphertext");
        String nonce = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.nonce");

        try {
            String decryptData = new AesUtil(key.getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
            return  new JSONObject(decryptData);
            //TODO 业务校验
        } catch (Exception e) {
           throw new JeecgBootException("支付错误");
        }

    }


    public static void main(String[] args) {


    }
}
